<?php


namespace app\sapi\controller\v1;


use app\common\controller\Api;
use app\common\model\UserWithdrawalLog;
use app\common\model\User;
use services\WxwithdrawalService;
use think\Db;
use think\Cache;

class Withdrawal extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    public function withdrawalbak()
    {
        $this->error('系统升级中，敬请期待~');
        $wallet = input('money', 0);
        $user = User::get($this->auth->id);
        if (empty($user) || $user->status != 'normal' || $wallet > $user->money) {
            $this->error('余额不足');
        }
        if (!$user->mobile) $this->error('请先绑定店铺');
        $shop = Db::name('shop')->where('phone="'.$user->mobile.'"')->find();
        if (!$shop) $this->error('请先绑定店铺手机号');
        if ($wallet>=500) $this->error('单次提现不能超过500元');
        $extend['withdrawal_no'] = $this->generateNo(['biz_tag'=>'withdrawal_no','len'=>12,'int_prefix'=>5]);
        $extend['card_no'] = $shop['phone'];
        $res = UserWithdrawalLog::addLog($user, $wallet,$extend);
        if ($res) $this->success('提交成功，请等待审核');
        $this->error('提交失败');
    }

    public function withdrawal()
    {
        $log_mod = input('log_mod','wechat'); // 支付宝支付alipay,微信支付wechat
        $card_no = input('card_no',''); // 账号
        $real_name = input('real_name',''); // 账号
        $money = input('money', 0);
        if ($money>200) $this->error('单次提现不能超过200元');
        if ($money<0.1) $this->error('单次提现不能小于0.1元');
        if (!$log_mod) $this->error('缺少参数');
        // if (!$real_name) $this->error('请填写真实姓名');
        $user = (new \app\common\model\User())->where([
            'id' => $this->auth->id
        ])->find();
        if (empty($user) || $user->status != 'normal') $this->error('账户异常');
        if ($money <= 0 || $money > $user->money || $user->money<0) $this->error('余额不足');
        $user_withdrawal_log = Db::name('user_withdrawal_log')->where('user_id='.$this->auth->id.' and log_status in (0,1,2) and create_dt>"'.date('Y-m-d').'"')->order('id DESC')->select();
        $sum = 0;
        foreach ($user_withdrawal_log as $key => $value) {
            $sum+=$value['wallet'];
        }
        if (count($user_withdrawal_log)>=5) $this->error('今日提现次数已满，可明天再提现');
        if ($sum>300) $this->error('今日提现额度已满，可明天再提现');

        
        $list = Db::name('user_withdrawal_log')->where(['user_id '=>$this->auth->id,'log_status'=>1,'wallet'=>$money])->find();
        if (time()-$list['with_time']<3) {
            $this->error('您操作太快啦，请稍后再试');
        }
        $extend['log_mod'] = $log_mod;
        $extend['card_no'] = $card_no;
        $extend['real_name'] = $real_name;
        $extend['withdrawal_no'] = $this->generateNo(['biz_tag'=>'withdrawal_no','len'=>12,'int_prefix'=>5]);
        // if ($real_name) {
        //     (new UserService())->setBlackList($this->auth->id,$real_name,'关键字');
        // }
        // if ($card_no) {
        //     (new UserService())->setBlackList($this->auth->id,$card_no,'支付宝账号');
        // }
        Db::startTrans();
        // try {
            $user = (new \app\common\model\User())->lock(true)->where([
                'id' => $this->auth->id
            ])->find();
            $res = $this->addWithdrawalLog($user, $money,'' ,$extend);
            $error = '';
            if (isset($res['status'])) {
                Db::rollback();
                $error = $res['msg'];
            }
            if (!$res) {
                Db::rollback();
                $error = '提交失败';
            }
            Db::commit();
        // } catch (\Exception $e) {
        //     Db::rollback();
        //     $this->error('提现失败请联系客服');
        // }
        if ($error) {
            $this->error($error);
        }
        $this->success('提交成功');
    }

    public function addWithdrawalLog($user, $wallet, $desc = '', $extend = [])
    {
        Db::startTrans();
        // try {
            $before = $user->money;
            $after = bcsub($before, $wallet,2);
            $data = [
                'log_mod' => $extend['log_mod'],
                'card_no' => $extend['card_no'],
                'real_name' => $extend['real_name'],
                'withdrawal_no' => $extend['withdrawal_no'],
                'user_id' => $user->id,
                'log_type' => 1,
                'wallet' => $wallet,
                'before_wallet' => $before,
                'after_wallet' => $after,
                'with_time' => time(),
                'with_desc' => $desc,
                'log_status' => 0,
                'is_merchant' => 0
            ];
            $log = UserWithdrawalLog::create($data);
            if (!$log) {Db::rollback();return false;}
            $money = $wallet;
            User::money($money, $user->id, '提现', $log['id'], 1);
            // 获取公钥
            $WxwithdrawalService = new WxwithdrawalService();
            $publickey = Cache::get('publickey');
            if (!$publickey) {
                // 获取微信证书
                $res = $WxwithdrawalService->certificates();
                $certificates = json_decode($res,1);
                $Aes = new \fast\AesUtil(config('jmgzh.mch_key'));
                $associatedData = $certificates['data'][0]['encrypt_certificate']['associated_data'];
                $nonceStr = $certificates['data'][0]['encrypt_certificate']['nonce'];
                $ciphertext = $certificates['data'][0]['encrypt_certificate']['ciphertext'];
                // 解析公钥
                $publickey = $Aes->decryptToString($associatedData, $nonceStr, $ciphertext); 
                Cache::set('publickey',$publickey,86400);
            }
            $unionid = User::where('id',$log['user_id'])->value('unionid');
            $openid = $user['openid'];
            $appid=config('jmgzh.appid');
            if (!$openid) {
                return ['status'=>0 ,'msg'=>'无法获得授权，请联系客服处理！'];
            }
            //请求参数,大于0.3要传姓名
            if ($log['wallet']<=0.3 || in_array($extend['real_name'], ['SHEE KAI YING','JCHANGLOCK','李䶮'])) {
                $data = [
                    'appid'=>$appid,
                    'out_batch_no'=>strval($log['withdrawal_no']),
                    'batch_name' => '爆单宝商家提现',
                    'batch_remark' => '爆单宝商家提现',
                    'total_amount' => intval(strval($log['wallet']*100)),
                    'total_num' => 1,
                    'transfer_detail_list'=>[[
                        'out_detail_no' => strval($log['withdrawal_no']),
                        'transfer_amount'=>intval(strval($log['wallet']*100)),
                        'transfer_remark'=>'爆单宝商家提现',
                        'openid' => $openid,
                    ]],
                    'notify_url' => config('api_domain').'/index/yunzhan/txNotify'
                ];
            } else {
                if (!isset($extend['real_name']) || !$extend['real_name']) {
                    Db::rollback();
                    return ['status'=>0 ,'msg'=>'请填写真实姓名']; 
                }
                $data = [
                    'appid'=>$appid,
                    'out_batch_no'=>strval($log['withdrawal_no']),
                    'batch_name' => '爆单宝商家提现',
                    'batch_remark' => '爆单宝商家提现',
                    'total_amount' => intval(strval($log['wallet']*100)),
                    'total_num' => 1,
                    'transfer_detail_list'=>[[
                        'out_detail_no' => strval($log['withdrawal_no']),
                        'transfer_amount'=>intval(strval($log['wallet']*100)),
                        'transfer_remark'=>'爆单宝商家提现',
                        'openid' => $openid,
                        'user_name' => $WxwithdrawalService->getEncrypt($extend['real_name'],$publickey),
                    ]],
                    'notify_url' => config('api_domain').'/index/yunzhan/txNotify'
                ];
            }
            $res = $WxwithdrawalService->transfer($data);
            if(!isset($res['create_time'])) {//批次受理失败
                Db::rollback();
                return false;
            } else {
                // 审核通过
                // $result = $log->allowField(true)->save([
                //     'log_status' => 1,
                //     'handel_admin_id' => $user->id,
                //     'handel_time' => time(),
                //     'batch_id' => $res['batch_id'],
                // ]);
            }
            Db::commit();
            return true;
        // } catch (Exception $e) {
        //     Db::rollback();
        //     return false;
        // }
    }






}